package main

import (
	"fmt"
	"math/rand"
	"time"
	"os"
	"strconv"
	"bufio"
)

func writeDataToFile(filename string, exitChan chan bool) {

	file, _ := os.Create(filename)
	defer file.Close()

	var number int
	rand.Seed(time.Now().UnixNano())

	for i := 0; i < 1000; i++ {
		number = rand.Intn(101)
		file.WriteString(strconv.Itoa(number) + "\n")
	}

	time.Sleep(time.Second)
	exitChan <- true

}

func bubbleSort(arr *[1000]int) {

	for i := 0; i < len(*arr) - 1; i ++ {

		for j := 0; j < len(*arr) - 1 - i; j++ {

			if (*arr)[j] > (*arr)[j + 1] {
				(*arr)[j], (*arr)[j + 1] = (*arr)[j + 1], (*arr)[j]
			}

		}

	}

}

func sort(filename string) {

	file, _ := os.Open(filename)

	scanner := bufio.NewScanner(file)
	var arr [1000]int
	index := 0
	for scanner.Scan() {
		num, _ := strconv.Atoi(scanner.Text())
		arr[index] = num
		index++
	}

	bubbleSort(&arr)
	file.Close()

	file2, _ := os.OpenFile(filename, os.O_WRONLY | os.O_TRUNC, 0644)
	defer file2.Close()

	for i := 0; i < len(arr); i++ {
		file2.WriteString(strconv.Itoa(arr[i]) + "\n")
	} 


}

func main() {

	var exitChan chan bool
	exitChan = make(chan bool, 1)

	for i := 0; i < 10; i++ {
		filename := "a" + fmt.Sprintf("%d", i) + ".txt"
		go writeDataToFile(filename, exitChan)
		for {
			_, ok := <- exitChan
			if ok {
				break
			}
		}
		go sort(filename)
	}
}